//Written by Aneesh and Jonathan

#include "appt.h"

string Appt::APPT = "appt";
string Appt::DAY = "day";
string Appt::TIME = "time";
string Appt::SUBJECT = "subject";
Appt::Appt(){
	
}

Appt::Appt(int day, double start, double end, const string& description) 
// For some reason this initializer list will not compile
// :myDate(day), myStart(start), myEnd(end), myDescription(description)
{
  	myDate=day;
  	myStart=start;
  	myEnd=end;
  	myDescription=description;
  	
	unsigned int i=0;
	int sum=0;
	while(i<description.size()-1) {
		sum+=((int)description[i+1]%2+1)*(int)description[i]+((int)description[i]%2+2)*(int)description[i+1];
		i+=2;
	}
	
	myHash=sum;
}

void Appt::readAppt(string myFileName, vector<Event*> myEvents)
{
	ifstream f(myFileName.c_str());
	string node;
	string temp;
	while(!f.eof())
	{
		getline(f,temp, '<');
		getline(f,node, '>');
		if(node.at(1)!='!')
		{
			readNodeAppt(node, myEvents);
		}	
	}
}

void Appt::readNodeAppt(const string& node, vector<Event*> myEvents  )
{
	string tempDay = getInfoAppt(node,DAY);
	string tempSubject = getInfoAppt(node,SUBJECT);
	int range[2]; 
	getTimeRangeAppt(node, TIME, range);
	myEvents.push_back(new Appt(atoi(tempDay.c_str()),range[0], range[1],tempSubject));
	
}

string Appt::getInfoAppt(const string& node, const string& infoType)
{
	unsigned int loc = node.find(infoType,0);
	if(loc != string::npos)
	{
		int start = node.find('\"', loc);
		int end = node.find('\"', start+1);
		return(node.substr(start+1,end-start-1));
	}
	return "Type not found";
}

void Appt::getTimeRangeAppt(const string& node, const string& infoType, int range[])
{
	range[0] = 0;
	range[1] = 0;

	unsigned int loc = node.find(infoType,0);
	if(loc != string::npos)
	{
		int start = node.find("\"",loc);
		int end = node.find("\"", start + 1);
		seperateTime(range, node.substr(start+1,end-start-1));
		
	}
}

void Appt::seperateTime(int range[], const string& times)
{
	unsigned int loc = times.find(".",0);
	unsigned int loc2 = times.find(",",0);
	if(loc != string::npos)
	{
		string temp = times.substr(0, loc);
		range[0]= atoi(temp.c_str());
		temp = times.substr(loc+1,times.length());
		range[1] = atoi(temp.c_str());
	}
	else if(loc2 != string::npos)
	{
		string temp = times.substr(0, loc2-1);
		range[0]= atoi(temp.c_str());
		temp = times.substr(loc2+1,times.length());
		range[1] = atoi(temp.c_str());
	}
}

